package cn.maple.transactionMessge;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

public class TransactionMessageConsumer {
    public static void main(String[] args) throws Exception {
        //同步消息消费
        TransactionMessage();

    }

    /**
     * syncMessage
     * 同步消息消费
     * @throws Exception
     */
    public static void TransactionMessage() throws Exception {
        // 实例化消费者Consumer
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("TransactionMessage-Consumer"/*消费者组名*/);

        // 设置NameServer的地址
        consumer.setNamesrvAddr("localhost:9876");
        consumer.subscribe("TransactionMessage", "*");
        // 设置事务监听器
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                try {
                    list.forEach(list1-> System.out.println(list1));
                    System.out.println(consumeConcurrentlyContext.toString());
                    // 标记该消息已经被成功消费
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                } catch (Exception e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            }
        });
        // 订阅一个或者多个Topic，以及Tag来过滤需要消费的消息


        // 启动消费者实例
        consumer.start();

    }


}
